package com.fastjars.business.upload;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * ConfigManager
 *
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/04/16
 * @version 1.0.0
 */
public class ConfigManager {
    private final static String CONFIG_FILE_NAME = "config.json";
    // 涂鸦上传filename定义
    private final static String SCRAWL_FILE_NAME = "scrawl";
    // 远程图片抓取filename定义
    private final static String REMOTE_FILE_NAME = "remote";

    private final String rootPath;
    private final String originalPath;
    private final String contextPath;
    private String parentPath = null;
    private JSONObject jsonConfig = null;

    public ConfigManager(String rootPath, String contextPath, String uri) throws IOException {
        this.rootPath = rootPath.replace(ActionHandler.FILE_BACKSLASH, ActionHandler.FILE_SEPARATOR);
        this.originalPath = this.rootPath + uri.replace(contextPath, "");
        this.contextPath = contextPath;
        this.initConfig();
    }

    public static ConfigManager me(String rootPath, String contextPath, String uri) {
        try {
            return new ConfigManager(rootPath, contextPath, uri);
        } catch (Exception e) {
            return null;
        }
    }

    public boolean valid() {
        return this.jsonConfig != null;
    }

    public JSONObject getAllConfig() {
        return this.jsonConfig;
    }

    public Map<String, Object> getConfig(int action) {
        Map<String, Object> conf = new HashMap<String, Object>();
        String savePath = null;
        switch (action) {
            case Action.UPLOAD_FILE:
                conf.put("isBase64", "false");
                conf.put("maxSize", this.jsonConfig.getLong("fileMaxSize"));
                conf.put("allowFiles", this.getArray("fileAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("fileFieldName"));
                savePath = this.jsonConfig.getString("filePathFormat");
                break;
            case Action.UPLOAD_ADDON:
                conf.put("isBase64", "false");
                conf.put("maxSize", this.jsonConfig.getLong("addonMaxSize"));
                conf.put("allowFiles", this.getArray("addonAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("addonFieldName"));
                savePath = this.jsonConfig.getString("addonPathFormat");
                break;
            case Action.READ_WORD:
                conf.put("isBase64", "false");
                conf.put("maxSize", this.jsonConfig.getLong("fileMaxSize"));
                conf.put("allowFiles", this.getArray("wordAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("fileFieldName"));
                savePath = this.jsonConfig.getString("wordPathFormat");
                break;
            case Action.UPLOAD_IMAGE:
                conf.put("isBase64", "false");
                conf.put("maxSize", this.jsonConfig.getLong("imageMaxSize"));
                conf.put("allowFiles", this.getArray("imageAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("imageFieldName"));
                savePath = this.jsonConfig.getString("imagePathFormat");
                break;
            case Action.UPLOAD_VIDEO:
                conf.put("maxSize", this.jsonConfig.getLong("videoMaxSize"));
                conf.put("allowFiles", this.getArray("videoAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("videoFieldName"));
                savePath = this.jsonConfig.getString("videoPathFormat");
                break;
            case Action.UPLOAD_SCRAWL:
                conf.put("filename", ConfigManager.SCRAWL_FILE_NAME);
                conf.put("maxSize", this.jsonConfig.getLong("scrawlMaxSize"));
                conf.put("fieldName", this.jsonConfig.getString("scrawlFieldName"));
                conf.put("isBase64", "true");
                savePath = this.jsonConfig.getString("scrawlPathFormat");
                break;
            case Action.CATCH_IMAGE:
                conf.put("filename", ConfigManager.REMOTE_FILE_NAME);
                conf.put("filter", this.getArray("catcherLocalDomain"));
                conf.put("maxSize", this.jsonConfig.getLong("catcherMaxSize"));
                conf.put("allowFiles", this.getArray("catcherAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("catcherFieldName") + "[]");
                savePath = this.jsonConfig.getString("catcherPathFormat");
                break;
            case Action.LIST_IMAGE:
                conf.put("allowFiles", this.getArray("imageManagerAllowFiles"));
                conf.put("dir", this.jsonConfig.getString("imageManagerListPath"));
                conf.put("count", this.jsonConfig.getIntValue("imageManagerListSize"));
                break;
            case Action.LIST_FILE:
                conf.put("allowFiles", this.getArray("fileManagerAllowFiles"));
                conf.put("dir", this.jsonConfig.getString("fileManagerListPath"));
                conf.put("count", this.jsonConfig.getIntValue("fileManagerListSize"));
                break;
        }
        conf.put(ActionHandler.PARAM_SAVE_PATH, savePath);
        conf.put(ActionHandler.PARAM_ROOT_PATH, this.rootPath);
        return conf;
    }

    public static String getRootPath(HttpServletRequest request, Map<String, Object> conf) {
        Object rootPath = request.getAttribute(ActionHandler.PARAM_ROOT_PATH);
        if (rootPath != null) {
            return rootPath + "" + File.separatorChar;
        } else {
            return conf.get(ActionHandler.PARAM_ROOT_PATH) + "";
        }
    }

    private String[] getArray(String key) {
        JSONArray jsonArray = this.jsonConfig.getJSONArray(key);
        String[] result = new String[jsonArray.size()];
        for (int i = 0, len = jsonArray.size(); i < len; i++) {
            result[i] = jsonArray.getString(i);
        }
        return result;
    }

    private void initConfig() throws IOException {
        File file = new File(this.originalPath);
        if (!file.isAbsolute()) {
            file = new File(file.getAbsolutePath());
        }
        this.parentPath = file.getParent();
        String configContent = this.readConfigFile(this.getConfigPath());
        try {
            JSONObject jsonConfig = JSONObject.parseObject(configContent);
            this.jsonConfig = jsonConfig;
        } catch (Exception e) {
            this.jsonConfig = null;
        }
    }

    private String getConfigPath() {
        String path = this.getClass().getResource(ActionHandler.FILE_SEPARATOR).getPath() + ConfigManager.CONFIG_FILE_NAME;
        if (new File(path).exists()) {
            return path;
        } else {
            return this.parentPath + File.separator + ConfigManager.CONFIG_FILE_NAME;
        }
    }

    /**
     * 读取配置文件
     *
     * @param path
     * @return
     * @throws IOException
     */
    private String readConfigFile(String path) throws IOException {
        StringBuilder builder = new StringBuilder();
        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
            BufferedReader bfReader = new BufferedReader(reader);
            String tmpContent = null;
            while ((tmpContent = bfReader.readLine()) != null) {
                builder.append(tmpContent);
            }
            bfReader.close();
        } catch (UnsupportedEncodingException e) {
            // 忽略
        }
        // TODO: 2018/04/16 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
        return builder.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "");
    }
}
